#include "stdafx.h"
#include "ShaderPhong1PL.h"

#include "DrawCall.h"
#include "RenderingData.h"
#include "Model.h"
#include "Material.h"

using namespace mgfx;

ShaderPhong1PL::ShaderPhong1PL()
{
	mVar_gTexture = NULL;
	mVar_gWVP = NULL;
	mVar_gDiffMat = NULL;
	mVar_gSpecMat = NULL;

	mVar_gAmbLight = NULL;
	mVar_gDiffLight = NULL;
	mVar_gSpecLight = NULL;
	mVar_gLightPosW = NULL;
	mVar_gEyePosW = NULL;

	mFilename = L"Phong1PL.fx";
}

bool ShaderPhong1PL::init()
{
	Tech = Effect->GetTechniqueByName("tech");

	mVar_gWVP =     Effect->GetVariableByName("gWVP")->AsMatrix();
	mVar_gWorld =   Effect->GetVariableByName("gWorld")->AsMatrix();
	mVar_gDiffMat = Effect->GetVariableByName("gDiffMat")->AsVector();
	mVar_gSpecMat = Effect->GetVariableByName("gSpecMat")->AsVector();

	mVar_gAmbLight =  Effect->GetVariableByName("gAmbLight")->AsVector();
	mVar_gDiffLight = Effect->GetVariableByName("gDiffLight")->AsVector();
	mVar_gSpecLight = Effect->GetVariableByName("gSpecLight")->AsVector();
	mVar_gLightPosW = Effect->GetVariableByName("gLightPosW")->AsVector();
	mVar_gEyePosW =   Effect->GetVariableByName("gEyePosW")->AsVector();

	mVar_gTexture = Effect->GetVariableByName("gDiffuseMap")->AsShaderResource();

	if(!Tech || ! mVar_gTexture || !mVar_gWVP)
		return false;
	else
	{
		mInitialized = true;
		return true;
	}
}

void ShaderPhong1PL::setParamsGlobal()
{
	RenderingData & data = RenderingData::Instance;
	mVar_gAmbLight->SetFloatVector(data.Pointlight.Ambient);
	mVar_gDiffLight->SetFloatVector(data.Pointlight.Diffuse);
	mVar_gSpecLight->SetFloatVector(data.Pointlight.Specular);
	mVar_gLightPosW->SetFloatVector(data.Pointlight.Position);
	mVar_gEyePosW->SetFloatVector((float*)&data.EyePosition);
}

void ShaderPhong1PL::setParamsModel(ModelDrawCall * drawCall)
{
	//XMMATRIX world = XMLoadFloat4x4(&drawCall->WorldMatrix);
	XMMATRIX world = drawCall->WorldMatrix;
	XMMATRIX viewProj = XMLoadFloat4x4(&RenderingData::Instance.ViewProj);
	world = XMMatrixMultiply(world, viewProj);

	//D3DXMATRIX wvp;
	//D3DXMatrixMultiply(&wvp, &drawCall->WorldMatrix, &RenderingData::Instance.ViewProj);

	mVar_gWVP->SetMatrix((float*)&world);
	mVar_gWorld->SetMatrix((float*)&drawCall->WorldMatrix);

	Material * mat = drawCall->Model->getMaterial();
	mVar_gTexture->SetResource(mat->DiffuseMap);
	mVar_gDiffMat->SetFloatVector(mat->DiffuseColor);
	mVar_gSpecMat->SetFloatVector(mat->SpecularColor);
}